﻿using System;
using System.Collections.Generic;
using System.Net.Mail;
using KillBill.Business.Entities;
using KillBill.Services.DTO;

namespace KillBill.Business.Modules.Administration
{
    public class MailManager
    {
        private static Dictionary<string, Parameter> _parameters;
        private static Dictionary<string, Parameter> Parameters
        {
            get
            {
                if (_parameters == null)
                    LoadData();
                return _parameters;
            }
        }
        private static void LoadData()
        {
            var administrationManager = new AdministrationManager();
            var allParameters = administrationManager.GetParameters().Parameters;
            _parameters = new Dictionary<string, Parameter>();
            foreach (var parameter in allParameters)
            {
                _parameters.Add(parameter.ParameterID, parameter);
            }
        }
        public static KillBillDTO SendMail(List<string> to, List<string> cc, string subject, string message)
        {
            var outDto = new KillBillDTO();
            var administrationManager = new AdministrationManager();
            try
            {
                var mailMessage = new MailMessage();
                mailMessage.From = new MailAddress(Parameters["AUTO_ORDER_MAIL"].Value, Parameters["COMPANY"].Value);
                foreach (var sTo in to)
                {
                    mailMessage.To.Add(new MailAddress(sTo));
                }
                mailMessage.Subject = subject;
                foreach (var sCc in cc)
                {
                    mailMessage.CC.Add(new MailAddress(sCc));
                }
                mailMessage.Body = message + "\n\n\n________________________________________________________\n" +
                               "Este mail fue generado automáticamente por el sistema de Facturación KillBill, por favor no responder a esta dirección";

                var smtp = new SmtpClient();
                smtp.Host = Parameters["MAIL_SERVER"].Value;
                smtp.Credentials = new System.Net.NetworkCredential(Parameters["AUTO_MAIL_USER"].Value, Parameters["AUTO_MAIL_PASS"].Value);
                smtp.Send(mailMessage);
                outDto.Success = true;
                outDto.Messages.Add("Mensaje de pedido enviado con exito");
            }
            catch (Exception ex)
            {
                outDto.Success = false;
                outDto.Messages.Clear();
                outDto.Messages.Add("Error en el envío de mensajes");
                outDto.Messages.Add(ex.Message);
            }
            return outDto;
        }
    }
}
